/*
 * MainServerThread.java
 *
 * Created on August 11, 2006, 12:03 AM
 *
 */
package org.letva.copie.mainserver;

import java.io.*;
import java.net.*;
import java.util.*;
import org.letva.copie.common.message.Message;
import org.letva.copie.common.message.SubServerInfo;

/**
 *
 * @author Vuk Nikolic
 */
public class SubServerThread extends Thread {

	/** Creates a new instance of SubServerThread */
	public SubServerThread(Socket s, MainServer ms) {
		super("SubServerThread");
		mySocket = s;
		myMainServer = ms;
		myMainServer.writeLog("SubServerThread created.");
	}

	@Override
	public void run() {

		ObjectOutput out = null;
		ObjectInput in = null;
		try {
			out = new ObjectOutputStream(mySocket.getOutputStream());
			in = new ObjectInputStream(mySocket.getInputStream());

			Object inputMessage = null;

			while (!theEnd) {

				inputMessage = (Message) in.readObject();

				Object outputMessage = myProtocol.processInput(inputMessage);
				out.writeObject(outputMessage);
				out.flush();
			}
			// posto je gotov, da izbrisemo ovaj subServer.

		} catch (SocketException ex) {
			myMainServer.writeLog("SubServerThread: Lost connection with subserver: " + mySocket.getInetAddress().toString());
		} catch (SocketTimeoutException ex) {
			myMainServer.writeLog("SubServerThread: Subserver timeout: " + mySocket.getInetAddress().toString());
		} catch (IOException e) {
			myMainServer.writeLog("SubServerThread: Problems with input/output operations");
		} catch (ClassNotFoundException ex) {
			myMainServer.getMyWindow().setDialogException("Internal Error", "ClassNotFound");
			myMainServer.writeLog("SubServerThread: ClassNotFound");
		}

		myMainServer.decActiveSubServerThreads();
		Map<String, SubServerInfo> subServers = myMainServer.getSubServers();
		String subServerUrl = mySocket.getInetAddress().toString();
		subServers.remove(subServerUrl);
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
			if (mySocket != null) {
				mySocket.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		myMainServer.writeLog("SubServerThread: finished");
	}
	// otvoreni mySocket sa kojim radi
	private Socket mySocket = null;
	// protocol po kome rade
	private MainServerProtocol myProtocol = MainServer.getProtocol();
	// koliko da ceka
	private int delay = 500;
	// mainServer
	private MainServer myMainServer = null;
	// fleg za kraj
	private boolean theEnd = false;
}
